package com._5704.website.service.ServiceImpl;

import com._5704.website.entity.Activity;
import com._5704.website.exception.WebsiteException;
import com._5704.website.exception.WebsiteExceptionEnum;
import com._5704.website.form.ActivityForm;
import com._5704.website.mapper.ActivityMapper;
import com._5704.website.service.IActivityService;
import com._5704.website.util.PictureUtil;
import com._5704.website.util.FileUtil;
import com._5704.website.util.RedisUtil;
import com._5704.website.vo.activityVO.ActivityVO;
import com._5704.website.vo.userVO.UserVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yiyoung
 * @since 2021-07-25
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {

    @Resource
    private ActivityMapper activityMapper;
    @Value("${download.activityPath}")
    private  String activityPath;
    @Resource
    private FileUtil fileUtil;
    /**
     * 获得多个用户
     *
     * @param
     * @param page 页数
     * @param num 数量
     * @param isGetAll 是否获得所有
     * @return 活动list
     */
    @Override
    public List<Activity> getActivities(int page, int num, int type, boolean isGetAll) {
        List<Activity> activityList ;


        String hKey = String.valueOf(page)+ num +type;
        // 是否是获得所有活动
        if (isGetAll){
            String key = "activity:isGetAll=true";

            if (RedisUtil.isExist(key,hKey)){
                activityList = RedisUtil.getValue(key,hKey);
            }else{
                // 是否是不分类
                if (type == 0) {
                    activityList = activityMapper.getAllActivities(page, num);
               // 按照类型
                }else{
                    activityList = activityMapper.getAllActivitiesByType(page, num,type);
                }
                RedisUtil.setValue(key,hKey,activityList);
            }
        }else {
            String key = "activity:isGetAll=false";
            // 是否是不分类
            if (RedisUtil.isExist(key,hKey)){
                activityList = RedisUtil.getValue(key,hKey);
            }else{
                if (type == 0) {
                    activityList = activityMapper.getPublicActivities(page, num);
                 // 按照类型
                }else{
                     activityList = activityMapper.getPublicActivitiesByType(page, num,type);
                }
                RedisUtil.setValue(key,hKey,activityList);
            }
        }
        return activityList;
    }

    /**
     * 根据id获得活动
     *
     * @param id 活动id
     * @return
     */
    @Override
    public Activity getActivity(Integer id) {
        Activity activity;
        String key = "activity:"+id;
        if (RedisUtil.isExist(key)){
            activity = RedisUtil.getValue(key);
        }else{
            activity = activityMapper.selectById(id);
            // 活动不存在
            if (activity == null) {
                throw new WebsiteException(WebsiteExceptionEnum.ACTIVITY_NOT_FOUND);
            }
            RedisUtil.setValue(key,activity);
        }
        return activity;
    }

    /**
     * 是否展示
     * @param activity 活动
     * @param userId 用户id
     */
    @Override
    public boolean isShow(Activity activity,String userId) {
        Date showTime = activity.getShowTime();
        // 活动允许展示，或者用户为发布人员，允许查看活动
        return showTime.before(new Date()) ||  activity.getUser().equals(userId) ;
    }

    /**
     * 创建新的活动
     *
     * @param activityForm 活动表单
     */
    @Override
    public void createActivity(ActivityForm activityForm, String userId) {
        String fileUid = UUID.randomUUID().toString();
        List<String> pictureList = activityForm.getPicture();

        //清理缓存
        RedisUtil.delete("activity:isGetAll=true");
        RedisUtil.delete("activity:isGetAll=true");
        RedisUtil.delete("activity:isGetAll=false");
        RedisUtil.delete("activity:isGetAll=false");


        // 从文章内容获得图片
        Queue<String> pictureQueue = fileUtil.getFromContent(activityForm.getContent(), activityPath);
        pictureQueue.forEach(e->{
                String src = activityPath + fileUid +"/"+ e.replace(activityPath,"");
                fileUtil.move(e,src);
                activityForm.setContent(activityForm.getContent().replace(e,src));
        });
        String  content =  activityForm.getContent();
        // 删除未使用的图片


        pictureList = pictureList.stream().filter(e->{
            boolean flag = true;
            for (String el : pictureQueue) {
                if(e.equals(el)){
                    flag = false;
                    break;
                }
            }
            return flag;
        }).collect(Collectors.toList());

        fileUtil.delete(pictureList,"");


        // 上传文件

        String contentName = activityPath + fileUid + "/content.html";

        fileUtil.upload(content,contentName);
        // 赋值
        Activity activity = new Activity()
                .setTitle(activityForm.getTitle())
                .setContent(contentName)
                .setActiveTime(activityForm.getActiveTime())
                .setShowTime(activityForm.getShowTime())
                .setUser(userId)
                .setType(activityForm.getType())
                .setPeople(activityForm.getPeople())
                .setPicture(fileUid)
                .setIsPublic(activityForm.getIsPublic())
                .setCreateTime(new Date());

        activityMapper.insert(activity);
        RedisUtil.setValue("activity:"+activity.getId(),activity);
    }

    /**
     * 删除活动
     *
     * @param activity 活动id
     */
    @Override
    public void delete(Activity activity) {
        // 删除文件
        fileUtil.delete(activityPath + activity.getPicture());


        activityMapper.deleteById(activity);

        //清理缓存
        RedisUtil.delete("activity:isGetAll=true");
        RedisUtil.delete("activity:isGetAll=true");
        RedisUtil.delete("activity:isGetAll=false");
        RedisUtil.delete("activity:isGetAll=false");
        RedisUtil.delete("activity:"+activity.getId());

    }

    /**
     * 设置更新活动
     *
     * @param activity     活动
     * @param activityForm 活动表单
     */
    @Override
    public void setModifyData(Activity activity, ActivityForm activityForm) {
        List<String>  pictureList =  activityForm.getPicture();
        String oldContent = fileUtil.download(activity.getContent());
        // 从文章内容获得图片
        Queue<String> pictureQueueNew = fileUtil.getFromContent(activityForm.getContent(), activityPath);
        Queue<String> pictureQueueOld = fileUtil.getFromContent(oldContent, activityPath);



        List<String>  list = new ArrayList<>(pictureQueueOld);
        list.addAll(pictureList);
        list = list.stream().filter(e->{
            boolean flag = true;
            for (String el : pictureQueueNew) {
                if(e.equals(el)){
                    flag = false;
                    break;
                }
            }
            return flag;
        }).collect(Collectors.toList());
        // 删除未使用的照片
        fileUtil.delete(list,"");

        // 获得提交照片list中使用的照片
        pictureList.forEach(e ->{
            pictureQueueNew.forEach(el -> {
                if (e.equals(el)){
                    //将照片移到目录
                    String src = activityPath + activity.getPicture() +"/"+ e.replace(activityPath,"");
                    fileUtil.move(e,src);
                    // 修改文章内容
                    activityForm.setContent(activityForm.getContent().replace(e,src));
                // 提交照片中未使用
                }
            });
        });

        // 更新文档
        String  content =  activityForm.getContent();
        fileUtil.upload(content,activity.getContent());


        activity.setActiveTime(activityForm.getActiveTime())
                .setTitle(activityForm.getTitle())
                .setType(activityForm.getType())
                .setPeople(activityForm.getPeople())
                .setIsPublic(activityForm.getIsPublic())
                .setShowTime(activityForm.getShowTime());
    }

    /**
     * 更新活动
     *
     * @param activity 活动
     */
    @Override
    public void updateActivity(Activity activity) {
        activityMapper.updateById(activity);

        RedisUtil.delete("activity:isGetAll=true");
        RedisUtil.delete("activity:isGetAll=true");
        RedisUtil.delete("activity:isGetAll=false");
        RedisUtil.delete("activity:isGetAll=false");
        RedisUtil.setValue("activity:"+activity.getId(),activity);

    }

    /**
     * 获得数量
     *
     * @return
     */
    @Override
    public int getNum(int type, boolean isGetAll) {
        int num;
        if (isGetAll){
            if (type == 0){
                num = activityMapper.getAllNum();
            }else{
                num = activityMapper.getAllNumByType(type);
            }
        }else{
            if (type == 0){
                num = activityMapper.getPublicNum();
            }else{
                num = activityMapper.getPublicNumByType(type);
            }
        }

        return num;
    }


    /**
     * 搜索
     *
     * @param name 名字
     * @param page 页面
     * @param num  数量
     * @return
     */
    @Override
    public List<Activity> getActivityByName(String name, int page, int num) {
        return activityMapper.getActivityByName(name,page,num);
    }

    /**
     * 获得数量
     *
     * @param name
     * @return
     */
    @Override
    public int getNum(String name) {
        return activityMapper.getSearchNum(name);
    }

    /**
     * 获得VO
     *
     * @param activity
     * @return
     */
    @Override
    public ActivityVO getActivityVO(Activity activity, UserVO userVO) {
        String content = fileUtil.download(activity.getContent());




        return new ActivityVO()
                .setIsPublic(activity.getIsPublic())
                .setActiveTime(activity.getActiveTime())
                .setContent(content)
                .setTitle(activity.getTitle())
                .setType(activity.getType())
                .setId(activity.getId())
                .setPeople(activity.getPeople())
                .setUser(userVO)
                .setShowTime(activity.getShowTime())
                .setCreateTime(activity.getCreateTime());
    }


    /**
     * 更新图片
     *  @param file 文件
     * @return*/
    @Override
    public String uploadPic(MultipartFile file) {
        if (file.isEmpty()){
            throw new WebsiteException(WebsiteExceptionEnum.FILE_ERROR);
        }
        String id = UUID.randomUUID().toString();
        // 设置数据库文件名
        String DataBaseFileName = "activity/id"+id + ".png";
        // 获得完整文件名称

        // 工具类上传
        fileUtil.upload(file,DataBaseFileName);
        // 修改数据库
//        activityMapper.updatePic(DataBaseFileName,id);

        return DataBaseFileName;
    }
}
